<template>
  <el-dialog
    :title="title+'商机'"
    append-to-body
    :visible="visible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="form" class="myform" :rules="rules" :model="form" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商机名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商机名称" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商机所有人" prop="owner">
            <el-input v-model="form.owner" placeholder="请输入姓名" disabled maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名" prop="customerId">
            <VbSelect v-model="form.customerId" :name="form.customerName" style="width:100%" :load-data="loadData" />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              style="width:100%"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商机类型" prop="type">
            <el-select v-model="form.type" style="width:100%">
              <el-option v-for="cs in chanceTypes" :key="cs.value" :value="cs.value" :label="cs.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售阶段" prop="saleStage">
            <el-select v-model="form.saleStage" style="width:100%">
              <el-option v-for="cs in saleStages" :key="cs.value" :value="cs.value" :label="cs.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="市场活动" prop="marketActivity">
            <el-input v-model="form.marketActivity" placeholder="请输入市场活动" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商机来源" prop="source">
            <el-select v-model="form.source" style="width:100%">
              <el-option v-for="cs in clueSource" :key="cs.value" :value="cs.value" :label="cs.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="金额（元）" prop="amount">
            <el-input v-model="form.amount" v-checkMoney maxlength="11" placeholder="请输入金额" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="255" :rows="6" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="text-align:right">
        <el-button plain @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>

      </el-row>
    </el-form>

  </el-dialog>
</template>
<script>
import BigNumber from 'bignumber.js'

import { clueStatus, clueSource, chanceTypes, saleStages } from '@/utils/enums'
import { updateChance, addChance } from '@/api/chance'
import { getCustomerSelect } from '@/api/customer'
import dayjs from 'dayjs'
export default {
  name: 'AddChanceDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }

  },
  data() {
    const validateDate = (rule, value, callback) => {
      if (dayjs(this.form.endDate).isBefore(dayjs(dayjs().format('YYYY-MM-DD')))) {
        callback(new Error('结束日期不能小于当前日期'))
      } else {
        callback()
      }
    }
    return {
      clueStatus,
      clueSource,
      saleStages,
      chanceTypes,
      form: {
        id: '',
        'amount': '',
        'customerId': '',
        'endDate': '',
        'marketActivity': '',
        'name': '',
        'remark': '',
        'saleStage': '',
        'source': '',
        'type': '',
        owner: ''

      },
      rules: {
        name: [
          { required: true, message: '商机名称不能为空', trigger: ['blur', 'change'] }
        ],
        customerId: [
          { required: true, message: '客户名不能为空', trigger: ['blur', 'change'] }
        ],
        endDate: [
          { required: true, message: '结束时间不能为空', trigger: ['blur', 'change'] },
          { validator: validateDate, trigger: 'blur' }

        ],
        saleStage: [
          { required: true, message: '销售阶段不能为空', trigger: ['blur', 'change'] }
        ],
        amount: [
          { required: true, message: '金额不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '修改' : '新建'
    }

  },
  mounted() {
    if (this.data.id) {
      // 修改
      this.form = JSON.parse(JSON.stringify(this.data))
      this.form.amount = this.data.amount ? BigNumber(this.data.amount).toFixed(2) : ''
    } else {
      this.form = {
        ...this.form,
        ...JSON.parse(JSON.stringify(this.data))
      }
      this.form.owner = this.USER.userName
    }
  },
  methods: {
    loadData(params) {
      return getCustomerSelect(params).then(res => {
        return res
      })
    },
    handleClose() {
      this.$emit('close')
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 有id 是修改
          // 处理amount
          const data = {
            ...this.form,
            amount: BigNumber(this.form.amount).toFixed(2)
          }
          if (this.data.id) {
            updateChance(data).then(res => {
              this.$emit('close', true)
              this.$message({
                type: 'success',
                message: '修改成功'
              })
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '修改失败'
              })
            })
          } else {
            addChance(data).then(res => {
              this.$emit('close', true)
              this.$message({
                type: 'success',
                message: '新增成功'
              })
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '新增失败'
              })
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.myform{
  padding: 0 20px;
}
</style>
